package com.qf.web;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 2019/11/18
 * Administrator
 * springmvc1118
 * 面向对象面向君  不负代码不负卿
 */
@Controller
public class FileController {
    @RequestMapping("/toupload")
    public String upload(MultipartFile myfile,
                         HttpServletRequest request,
                         ModelMap modelmap){
        //1.先得到上传的文件信息
        //得到文件名称
        String filename = myfile.getOriginalFilename();
        //得到服务器端的路径   /uploadimg
        //将字符串的路径转换成服务器端的路径
        String path = request.getRealPath("/uploadimg");
        System.out.println("path="+path);
        //结果: a.jpg     spring1118/uploadimg/a.jpg
        //2.实现文件上传
        try {
            myfile.transferTo(new File(path+"/"+filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        modelmap.addAttribute("imgname",filename);
        return "uploadsuccess";
    }


    //文件下载
    @RequestMapping("/download")
    public ResponseEntity<byte[]> down(String imagename,HttpServletRequest request){
        //1.获得被下载资源的完整路径
        String realPath = request.getRealPath("/uploadimg/" + imagename);
        try {
            //2.将路径所得到的文件转换成流信息
            //并且将流设置到响应的头信息中
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //设置以弹窗的方式提示用户下载,attachment 固定值 参数2表示文件名
            httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode(imagename,"UTF-8"));
            //3.响应信息
            ResponseEntity<byte[]> responseEntity =
                    new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(realPath)),httpHeaders, HttpStatus.CREATED);
            return responseEntity;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

            return null;
    }

}
